package com.shiyou.boke.controller;

import com.shiyou.boke.entity.BokeUser;
import com.shiyou.boke.service.IBokeUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.multipart.MultipartFile;
import cn.hutool.crypto.SecureUtil;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-07-01
 */
@RestController
@RequestMapping("/boke-user")
public class BokeUserController {
    @Autowired
    private IBokeUserService userService;

    @Value("${server.port}")
    @Autowired
    private String serverPort;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");
        String confirmPassword = body.get("confirmPassword");
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户名和密码不能为空");
        }
        if (!password.equals(confirmPassword)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("两次密码不一致");
        }
        // 检查用户名唯一
        //https://baomidou.com/guides/data-interface/

        if (userService.lambdaQuery().eq(BokeUser::getUsername, username).count() > 0) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("用户名已存在");
        }
        BokeUser user = new BokeUser();
        user.setUsername(username);
        user.setPasswordHash(SecureUtil.md5(password));
        userService.save(user);
        return ResponseEntity.ok("注册成功");
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户名和密码不能为空");
        }
        BokeUser user = userService.lambdaQuery().eq(BokeUser::getUsername, username).one();
        if (user == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户不存在");
        }
        if (!SecureUtil.md5(password).equals(user.getPasswordHash())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("密码错误");
        }
        // 登录成功，返回用户信息和token
        Map<String, Object> result = new HashMap<>();
        result.put("token", "user_token_" + user.getId() + "_" + System.currentTimeMillis()); // 简单的token生成
        result.put("id", user.getId());
        result.put("username", user.getUsername());
        result.put("email", user.getEmail());
        result.put("avatarUrl", user.getAvatarUrl());
        result.put("bio", user.getBio());
        return ResponseEntity.ok(result);
    }

    /**
     * 上传头像
     */
    @PostMapping("/upload-avatar")
    public ResponseEntity<?> uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam("userId") Long userId) {
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("请选择文件");
        }
        
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || (!contentType.startsWith("image/"))) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("只能上传图片文件");
        }
        
        // 检查文件大小 (限制为5MB)
        if (file.getSize() > 5 * 1024 * 1024) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("文件大小不能超过5MB");
        }
        
        try {
            // 创建上传目录
            String uploadDir = "uploads/avatars/";
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String filename = UUID.randomUUID().toString() + extension;
            
            // 保存文件
            Path filePath = Paths.get(uploadDir + filename);
            Files.copy(file.getInputStream(), filePath);
            
            // 更新用户头像URL
            String avatarUrl = "http://localhost:" + serverPort + "/uploads/avatars/" + filename;
            BokeUser user = userService.getById(userId);
            if (user != null) {
                user.setAvatarUrl(avatarUrl);
                userService.updateById(user);
                
                Map<String, Object> result = new HashMap<>();
                result.put("avatarUrl", avatarUrl);
                result.put("message", "头像上传成功");
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("用户不存在");
            }
            
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户资料
     */
    @PutMapping("/update-profile")
    public ResponseEntity<?> updateProfile(@RequestBody Map<String, Object> body) {
        Long userId = Long.valueOf(body.get("id").toString());
        String email = (String) body.get("email");
        String bio = (String) body.get("bio");
        
        BokeUser user = userService.getById(userId);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("用户不存在");
        }
        
        user.setEmail(email);
        user.setBio(bio);
        userService.updateById(user);
        
        return ResponseEntity.ok("资料更新成功");
    }
}
